﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

/*
* 命名空间:  TableToEntity.Logic
*
* 功 能：
*
* 类 名：CreateLogicFile  
*
* Version   变更日期            负责人     变更内容
* ─────────────────────────────────────────────────
* V1.0.1   2021/8/4 16:36:36  LW     创建
*
* Copyright (c) 2020 ZHDL Corporation. All rights reserved.
*/
namespace TableToEntity
{
    /// <summary>
    /// 创建逻辑实体
    /// </summary>
	public class CreateLogicFile
    {

        /// <summary>
        /// 生成Profile文件
        /// </summary>
        /// <param name="profileName"></param>
        public static void CreateProfile(DtoInfo dtoInfo)
        {
            string fileName = Path.Combine(dtoInfo.DtoFolder, dtoInfo.Profile + "Profile.cs");
            StringBuilder sb = new StringBuilder();
            using (StreamWriter sw = File.CreateText(fileName))
            {

                sb.AppendLine("using System;");
                sb.AppendLine("using AutoMapper;");
                sb.AppendLine("using Common.Library;");
                sb.AppendLine("using Common.Model;");

                sb.AppendLine("/*");
                sb.AppendLine(string.Format("* 命名空间: {0}", dtoInfo.NameSpace));
                sb.AppendLine("*");
                sb.AppendLine(string.Format(string.Format("* 功 能： {0}实体类映射帮助类", dtoInfo.Profile + "Profile")));
                sb.AppendLine("*");
                sb.AppendLine(string.Format("* 类 名： {0}", dtoInfo.Profile + "Profile"));
                sb.AppendLine("*");
                sb.AppendLine("* Version   变更日期           负责人     变更内容");
                sb.AppendLine("* ─────────────────────────────────────────────────");
                sb.AppendLine(string.Format("* V1.0.1    {0}     Harvey    创建", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
                sb.AppendLine("*");
                sb.AppendLine("* Copyright (c) 2021 Harvey Corporation. All rights reserved.");
                sb.AppendLine("*/");

                sb.AppendLine("");
                sb.AppendLine(string.Format("namespace {0}", dtoInfo.NameSpace));
                sb.AppendLine("{");
                sb.AppendLine("");
                sb.AppendLine("    /// <summary>");
                sb.AppendLine(string.Format("    /// {0}", dtoInfo.Profile + "实体类映射帮助类"));
                sb.AppendLine("    /// </summary>");
                sb.AppendLine(string.Format("    public class {0}Profile:Profile", dtoInfo.Profile));
                sb.AppendLine("    {");
                sb.AppendLine("       /// <summary>");
                sb.AppendLine("       /// 构造函数");
                sb.AppendLine("       /// </summary>");
                sb.AppendLine(string.Format("       public {0}Profile()", dtoInfo.Profile));
                sb.AppendLine("       {");
                sb.AppendLine("            //eg:CreateMap<from, to>().ForMember(p => p.type_name, opt => opt.MapFrom(x => (Convert.ToInt32(x.type)).GetEnumDescriptionByValue(typeof(DrainCompanyType))));");
                sb.AppendLine(string.Format("            CreateMap<{0}, {1}>();", dtoInfo.TableModel, dtoInfo.ResponseModel));
                sb.AppendLine(string.Format("            CreateMap<{0}, {1}>();", dtoInfo.ModifyModel, dtoInfo.TableModel));
                sb.AppendLine("        }");
                sb.AppendLine("    }");
                sb.AppendLine("}");

                sw.Write(sb.ToString());
                sb.Clear();
            }
        }

        /// <summary>
        /// 创建列表对应的逻辑文件
        /// </summary>
        /// <param name="dtoInfo"></param>
        public  static void CreateListLogic(DtoInfo dtoInfo)
        {

            string fileName = Path.Combine(dtoInfo.LogicFolder, dtoInfo.LogicName + "ServiceImpl.cs");
            StringBuilder sb = new StringBuilder();
            using (StreamWriter sw = File.CreateText(fileName))
            {
                sb.AppendLine("using Common.Library;");
                sb.AppendLine("using Common.Model;");
                sb.AppendLine("using Container.Library;");
                sb.AppendLine("using Dapper.Library;");
                sb.AppendLine("using Serialize.Library;");
                sb.AppendLine("using System;");
                sb.AppendLine("using System.Collections.Generic;");

                sb.AppendLine("");
                sb.AppendLine(string.Format("namespace {0}", dtoInfo.NameSpace));
                sb.AppendLine("{");
                sb.AppendLine("");
                sb.AppendLine("    /// <summary>");
                sb.AppendLine(string.Format("    /// {0}", dtoInfo.LogicName + "操作逻辑类"));
                sb.AppendLine("    /// </summary>");
                sb.AppendLine(string.Format("    public class {0}ServiceImpl:OperationLogicImpl,I{0}Service", dtoInfo.LogicName));
                sb.AppendLine("    {");

                #region 查询

                sb.AppendLine("       #region 查询");
                sb.AppendLine("       /// <summary>");
                sb.AppendLine("       ///根据关键字分页获取列表");
                sb.AppendLine("       /// </summary>");
                sb.AppendLine("       /// <param name=\"inputInfo\"></param>");
                sb.AppendLine("       /// <returns></returns>");
                sb.AppendLine(string.Format("       public ResultJsonInfo<List<{0}>> LoadPageList(ParametersInfo<{1}> inputInfo)", dtoInfo.ResponseModel, dtoInfo.QueryModel));
                sb.AppendLine("       {");
                sb.AppendLine(string.Format("          var resultInfo = new ResultJsonInfo<List<{0}>>();", dtoInfo.ResponseModel));
                sb.AppendLine("          using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))");
                sb.AppendLine("          {");
                sb.AppendLine("            int isDeleted = (int)IsDeleted.Deleted;");
                sb.AppendLine(string.Format("            var result = con.QuerySet<{0}>().Where(a => a.is_deleted != isDeleted);", dtoInfo.TableModel));

                //条件拼装
                sb.AppendLine("            if (inputInfo.parameters.xxx.IsNotNullOrEmpty())");
                sb.AppendLine("            {");
                sb.AppendLine("               result.Where(p => p.xxx.Equals(inputInfo.parameters.xxxx));");
                sb.AppendLine("            }");

                //排序
                sb.AppendLine("            #region 排序");
                sb.AppendLine("            if (inputInfo.field.IsNullOrEmpty())");
                sb.AppendLine("            {");
                sb.AppendLine("                inputInfo.field = \" sort\";");
                sb.AppendLine("            }");
                sb.AppendLine("            if (inputInfo.order.IsNullOrEmpty())");
                sb.AppendLine("            {");
                sb.AppendLine("                inputInfo.order = \" asc\";");
                sb.AppendLine("            }");
                sb.AppendLine("            if (inputInfo.order.ToLower() == \"asc\")");
                sb.AppendLine("            {");
                sb.AppendLine("                result.OrderBy(inputInfo.field);");
                sb.AppendLine("            }");
                sb.AppendLine("            else");
                sb.AppendLine("            {");
                sb.AppendLine("                result.OrderByDescing(inputInfo.field);");
                sb.AppendLine("            }");
                sb.AppendLine("            #endregion");
                sb.AppendLine("            //eg: var queryInfo = result.PageList(inputInfo.page, inputInfo.limit, p => new GoodsInfoEntity { id = p.id }); ");
                sb.AppendLine("            var queryInfo = result.PageList(inputInfo.page, inputInfo.limit);");
                sb.AppendLine("            if (queryInfo.Items.Count > 0)");
                sb.AppendLine("            {");
                sb.AppendLine("                resultInfo.Code = ActionCodes.Success;");
                sb.AppendLine(string.Format("                resultInfo.Data = queryInfo.Items.MapToList<{0}>();", dtoInfo.ResponseModel));
                sb.AppendLine("                resultInfo.Count = queryInfo.Total;");
                sb.AppendLine("                resultInfo.Msg = \"获取成功！\";");
                sb.AppendLine("            }");
                sb.AppendLine("            else");
                sb.AppendLine("            {");
                sb.AppendLine("                resultInfo.Msg = \"无对应值存在！\";");
                sb.AppendLine("            }");
                sb.AppendLine("         }");
                sb.AppendLine("         return resultInfo;");
                sb.AppendLine("       }");
                sb.AppendLine("       #endregion");

                //获取附件
                #region 获取附件
                sb.AppendLine("       ///// <summary>");
                sb.AppendLine("       ///// 根据XXXXid获取附件文件");
                sb.AppendLine("       ///// </summary>");
                sb.AppendLine("       ///// <param name=\"XXId\"></param>");
                sb.AppendLine("       ///// <returns></returns>");
                sb.AppendLine("       //public ResultJsonInfo<List<XXX>> LoadAttachList(string XXId)");
                sb.AppendLine("       //{");
                sb.AppendLine("       //    var resultInfo = new ResultJsonInfo<List<XXXX>>();");
                sb.AppendLine("       //    using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))");
                sb.AppendLine("       //    {");
                sb.AppendLine("       //        var listInfo = con.QuerySet<XXXX>()");
                sb.AppendLine("       //                .Where(a => a.xxid.Equals(XXId))");
                sb.AppendLine("       //                .OrderBy(p=>p.sort)");
                sb.AppendLine("       //                .ToList();");
                sb.AppendLine("       //        if (listInfo.Count > 0)");
                sb.AppendLine("       //        {");
                sb.AppendLine("       //            resultInfo.Code = ActionCodes.Success;");
                sb.AppendLine("       //            resultInfo.Data = listInfo;");
                sb.AppendLine("       //        }");
                sb.AppendLine("       //        else");
                sb.AppendLine("       //        {");
                sb.AppendLine("       //            resultInfo.Data = new List<XXXX>();");
                sb.AppendLine("       //            resultInfo.Msg = \"无对应信息！\";");
                sb.AppendLine("       //        }");
                sb.AppendLine("       //    }");
                sb.AppendLine("       //    return resultInfo;");
                sb.AppendLine("       //}");
                #endregion

                #endregion

                #region 更新
                sb.AppendLine("       #region 更新");

                sb.AppendLine("       /// <summary>");
                sb.AppendLine("       /// 更新");
                sb.AppendLine("       /// </summary>");
                sb.AppendLine("       /// <param name=\"inputInfo\"></param>");
                sb.AppendLine("       /// <returns></returns>");
                sb.AppendLine(string.Format("       public ResultJsonInfo<int> SaveInfo({0} inputInfo)", dtoInfo.ModifyModel));
                sb.AppendLine("       {");
                sb.AppendLine("          var resultInfo = new ResultJsonInfo<int>();");
                sb.AppendLine("          using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))");
                sb.AppendLine("          {");
                sb.AppendLine("             var result = 0;");
                sb.AppendLine("             if (inputInfo.id.IsNotNullOrEmpty())");
                sb.AppendLine("             {");

                #region #region Modify
                sb.AppendLine("                  #region Modify");
                sb.AppendLine(string.Format("                 var modifyInfo = con.QuerySet<{0}>().Where(p => p.id == inputInfo.id).Get();", dtoInfo.TableModel));
                sb.AppendLine("                  if (modifyInfo != null)");
                sb.AppendLine("                  {");
                sb.AppendLine("                      modifyInfo.xxx = inputInfo.xxx;");
                sb.AppendLine(string.Format("                      result = con.CommandSet<{0}>().Update(modifyInfo);", dtoInfo.TableModel));
                sb.AppendLine("                      if (result > 0)");
                sb.AppendLine("                      {");
                sb.AppendLine("                          resultInfo.Code = ActionCodes.Success;");
                sb.AppendLine("                          resultInfo.Msg = \"修改成功！\";");
                sb.AppendLine("                          AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.xxxxx, $\"修改xx信息，修改信息：{ JsonHelper.ToJson(inputInfo)}\");");
                sb.AppendLine("                      }");
                sb.AppendLine("                      else");
                sb.AppendLine("                      {");
                sb.AppendLine("                          resultInfo.Code = ActionCodes.InvalidOperation;");
                sb.AppendLine("                          resultInfo.Msg = \"修改失败！\";");
                sb.AppendLine("                      }");
                sb.AppendLine("                  }");
                sb.AppendLine("                  else");
                sb.AppendLine("                  {");
                sb.AppendLine("                      resultInfo.Code = ActionCodes.InvalidOperation;");
                sb.AppendLine("                      resultInfo.Msg = \"对应Id的信息不存在！\";");
                sb.AppendLine("                  }");
                sb.AppendLine("                  #endregion");
                #endregion

                sb.AppendLine("             }");
                sb.AppendLine("             else");
                sb.AppendLine("             {");

                #region region Add
                sb.AppendLine("                  #region Add");
                sb.AppendLine(string.Format("                  var addInfo = inputInfo.MapTo<{0}>();", dtoInfo.TableModel));
                sb.AppendLine("                  addInfo.id = GuidHelper.GetGuid();");
                sb.AppendLine(string.Format("                  result = con.CommandSet<{0}>().Insert(addInfo);", dtoInfo.TableModel));
                sb.AppendLine("                   if (result > 0)");
                sb.AppendLine("                   {");
                sb.AppendLine("                      resultInfo.Code = ActionCodes.Success;");
                sb.AppendLine("                      resultInfo.Msg = \"添加成功！\";");
                sb.AppendLine("                      AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.xxxx, $\"添加了一个xxxx信息，新增信息：{ JsonHelper.ToJson(inputInfo)}\");");
                sb.AppendLine("                   }");
                sb.AppendLine("                   else");
                sb.AppendLine("                   {");
                sb.AppendLine("                      resultInfo.Code = ActionCodes.InvalidOperation;");
                sb.AppendLine("                      resultInfo.Msg = \"添加失败！\";");
                sb.AppendLine("                   }");
                sb.AppendLine("                  #endregion");
                #endregion

                sb.AppendLine("             }");
                sb.AppendLine("         }");
                sb.AppendLine("         return resultInfo;");
                sb.AppendLine("      }");


                sb.AppendLine("       #endregion");
                #endregion

                #region 删除

                sb.AppendLine("       #region 删除");
                sb.AppendLine("       /// <summary>");
                sb.AppendLine("       /// 删除XXX信息");
                sb.AppendLine("       /// </summary>");
                sb.AppendLine("       /// <param name=\"ids\"></param>");
                sb.AppendLine("       /// <returns></returns>");
                sb.AppendLine("        public ResultJsonInfo<int> Remove(List<string> ids)");
                sb.AppendLine("        {");
                sb.AppendLine("             var resultInfo = new ResultJsonInfo<int>();");
                sb.AppendLine("             using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))");
                sb.AppendLine("             {");
                sb.AppendLine("                  //删除con.Transaction(tran =>{ });");
                sb.AppendLine("                  //var info = tran.QuerySet<GoodsInfoEntity>().Where(p => p.id.In(ids.ToArray())).ToList();");
                sb.AppendLine("                  //info.ForEach(a => a.is_deleted = (int)IsDeleted.Deleted);");
                sb.AppendLine("                  //var result = tran.CommandSet<GoodsInfoEntity>().Update(info);");
                sb.AppendLine(string.Format("                  var result = con.CommandSet<{0}>().Where(p => p.id.In(ids.ToArray())).Delete();", dtoInfo.TableModel));
                sb.AppendLine("                  if (result > 0)");
                sb.AppendLine("                  {");
                sb.AppendLine("                      ///con.CommandSet<XXXX>().Where(p => p.xxid.In(ids.ToArray())).Delete();");
                sb.AppendLine("                      resultInfo.Code = ActionCodes.Success;");
                sb.AppendLine("                      resultInfo.Msg = \"删除成功！\";");
                sb.AppendLine("                      AddOperationLog(OperationLogType.RemoveOperation, BusinessTitleType.XXXX, $\"删除XXX信息成功，物理删除信息：{ JsonHelper.ToJson(ids)}\");");
                sb.AppendLine("                  }");
                sb.AppendLine("                  else");
                sb.AppendLine("                  {");
                sb.AppendLine("                      resultInfo.Msg = \"删除失败！\";");
                sb.AppendLine("                  }");
                sb.AppendLine("             }");
                sb.AppendLine("             return resultInfo;");
                sb.AppendLine("        }");
                sb.AppendLine("       #endregion");
                #endregion

                sb.AppendLine("    }");
                sb.AppendLine("}");

                sw.Write(sb.ToString());
                sb.Clear();
            }
        }


        /// <summary>
        /// 创建列表类型的逻辑类接口文件
        /// </summary>
        public static void CreateListInterface(DtoInfo dtoInfo)
        {
            string fileName = Path.Combine(dtoInfo.LogicFolder, "I" + dtoInfo.LogicName + "Service.cs");
            StringBuilder sb = new StringBuilder();
            using (StreamWriter sw = File.CreateText(fileName))
            {
                sb.AppendLine("using Common.Model;");
                sb.AppendLine("using System.Collections.Generic;");

                sb.AppendLine("");
                sb.AppendLine(string.Format("namespace {0}", dtoInfo.NameSpace));
                sb.AppendLine("{");
                sb.AppendLine("");
                sb.AppendLine("    /// <summary>");
                sb.AppendLine(string.Format("    /// {0}", dtoInfo.LogicName + "操作逻辑类接口"));
                sb.AppendLine("    /// </summary>");
                sb.AppendLine(string.Format("    public interface I{0}Service", dtoInfo.LogicName));
                sb.AppendLine("    {");

                #region 查询

                sb.AppendLine("       #region 查询");
                sb.AppendLine("       /// <summary>");
                sb.AppendLine("       ///根据关键字分页获取列表");
                sb.AppendLine("       /// </summary>");
                sb.AppendLine("       /// <param name=\"inputInfo\"></param>");
                sb.AppendLine("       /// <returns></returns>");
                sb.AppendLine(string.Format("        ResultJsonInfo<List<{0}>> LoadPageList(ParametersInfo<{1}> inputInfo);", dtoInfo.ResponseModel, dtoInfo.QueryModel));
                sb.AppendLine("       #endregion");

                //获取附件
                #region 获取附件
                sb.AppendLine("       /////<summary>");
                sb.AppendLine("       /////根据XXXXid获取附件文件");
                sb.AppendLine("       /////</summary>");
                sb.AppendLine("       /////<param name=\"XXId\"></param>");
                sb.AppendLine("       /////<returns></returns>");
                sb.AppendLine("       //ResultJsonInfo<List<XXX>> LoadAttachList(string XXId);");
                #endregion

                #endregion

                #region 更新
                sb.AppendLine("       #region 更新");
                sb.AppendLine("       /// <summary>");
                sb.AppendLine("       /// 更新");
                sb.AppendLine("       /// </summary>");
                sb.AppendLine("       /// <param name=\"inputInfo\"></param>");
                sb.AppendLine("       /// <returns></returns>");
                sb.AppendLine(string.Format("       ResultJsonInfo<int> SaveInfo({0} inputInfo);", dtoInfo.ModifyModel));
                sb.AppendLine("       #endregion");
                #endregion

                #region 删除
                sb.AppendLine("       #region 删除");
                sb.AppendLine("       /// <summary>");
                sb.AppendLine("       /// 删除XXX信息");
                sb.AppendLine("       /// </summary>");
                sb.AppendLine("       /// <param name=\"ids\"></param>");
                sb.AppendLine("       /// <returns></returns>");
                sb.AppendLine("       ResultJsonInfo<int> Remove(List<string> ids);");
                sb.AppendLine("       #endregion");
                #endregion

                sb.AppendLine("    }");
                sb.AppendLine("}");

                sw.Write(sb.ToString());
                sb.Clear();

            }
        }
    }
}
